﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Specialized;

namespace ClickrDesktop.Managers
{
    class User
    {
        #region HttpRequestHelpers
        private HttpWebRequest getRequest(String method, String url)
        {
            HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
            req.Method = method;

            req.UserAgent = "Mozilla/5.0";

            req.AutomaticDecompression = DecompressionMethods.GZip;
            req.ServicePoint.Expect100Continue = false;

            return req;
        }

        private HttpWebRequest WritePostData(HttpWebRequest req, string strPostData, string contentType)
        {

            byte[] postData = Encoding.ASCII.GetBytes(strPostData);
            if (contentType == null)
                req.ContentType = "application/x-www-form-urlencoded";
            else
                req.ContentType = contentType;
            req.ContentLength = postData.Length;

            using (Stream outStream = req.GetRequestStream())
            {
                outStream.Write(postData, 0, postData.Length);
                outStream.Flush();
            }

            return req;
        }

        private string GetResponse(HttpWebRequest req)
        {
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            StreamReader rdr = new StreamReader(resp.GetResponseStream());
            string html = rdr.ReadToEnd();
            return html;
        }
        #endregion

        // User Login Routine
        public Models.User login(String username, String password)
        {
            try
            {
                string reqUrl = "http://www.clickr.butlr.com/index.php?ACT=30";
                HttpWebRequest req = getRequest("POST", reqUrl);
                string postData = string.Format("username={0}&password={1}&method=login", username, password);
                req = WritePostData(req, postData, null);
                string json = GetResponse(req);
                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                Models.User user = jsSerializer.Deserialize<Models.User>(json);

                return user;
            }
            catch (Exception ex)
            {
                Managers.LogManager.EnterInLogFile(String.Format("Exception\n{0}\n{1}", ex.Message, ex.StackTrace));
                return null;
            }
        }

        #region Export *.tpqx file to Clickr
        // Push Service
        public String pushXML(Models.User user, String file)
        {
            String method = "push";
            String reqUrl = "http://www.clickr.butlr.com/index.php?ACT=30";
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("session_id", user.session_id);
            nvc.Add("method", method);

            HttpWebRequest wr;
            String result = String.Empty;
            try
            {
                wr = HttpUploadFile(reqUrl, file, "poll_data_file", "text/xml", null, null, nvc);
                result = GetResponse(wr);
            }
            catch (Exception ex) { result = ex.Message; }

            return result;
        }
        public HttpWebRequest HttpUploadFile(string url, string file, string paramName, string contentType, string authToken, string cookies, NameValueCollection nvc)
        {
            string fileName = file.Substring(file.LastIndexOf(@"\") + 1);
            fileName = fileName.Substring(fileName.LastIndexOf(@"/") + 1);

            string boundary = "----WebKitFormBoundary8XKiLlUAdqSGSNQv";
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";

            wr.KeepAlive = true;
            wr.Headers["Authorization"] = authToken;
            wr.Headers["MIME-Version"] = "1.0";

            if (cookies != null)
                wr.Headers["Cookie"] = cookies;

            wr.Headers["Accept-Encoding"] = "gzip,deflate";
            wr.Accept = "application/json";
            wr.ServicePoint.Expect100Continue = false;

            Stream rs = wr.GetRequestStream();

            if (nvc != null)
            {
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (string key in nvc.Keys)
                {
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, key, nvc[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    rs.Write(formitembytes, 0, formitembytes.Length);
                }
            }

            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = string.Empty;
            string header = string.Empty;
            if (paramName == null || paramName == "")
            {
                headerTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
                header = string.Format(headerTemplate, fileName, contentType);
            }
            else
            {
                headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                header = string.Format(headerTemplate, paramName, fileName, contentType);
            }

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            return wr;
        }
        #endregion

        #region Import Poll
        // Push Results and Display in other form
        public String pull_polls(Models.User user)
        {
            String json = String.Empty;
            try
            {
                String url = "http://www.clickr.butlr.com/index.php?ACT=30&method=pull_polls&sid=" + user.session_id;
                
                CookieContainer cookieJar = new CookieContainer();
                HttpWebRequest request = null;
                HttpWebResponse response = null;

                // Bad Code But working. Why? No Idea....
                for (int i = 0; i < 2; i++)
                {
                    request = (HttpWebRequest)HttpWebRequest.Create(url);
                    request.CookieContainer = cookieJar;

                    request.ContentType = "application/json; charset=utf-8";
                    request.Credentials = CredentialCache.DefaultCredentials;

                    response = (HttpWebResponse)request.GetResponse();
                    StreamReader rdr = new StreamReader(response.GetResponseStream());
                    json = rdr.ReadToEnd();
                }
            }
            catch (Exception ex) { json = String.Empty; LogManager.EnterInLogFile(String.Format("Exception \n{0}\n{1}", ex.Message, ex.StackTrace)); }
            return json;
        }
        #endregion
    }
}
